package com.wolfking.jeesite.freemarker;

import com.wolfking.jeesite.config.SsoConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class TemplateRenderService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private SsoConfig ssoConfig;

    public String renderTemplate(String templateVal) {
        return renderTemplate(templateVal, getRootUrlMap());
    }
    public String renderTemplate(String templateVal, Object paramsModel) {
        String name = UUID.randomUUID().toString();
        try {
            StringWriter sw = new StringWriter();
            Template template = new Template(name, new StringReader(templateVal), configuration);
            template.process(paramsModel, sw);
            return sw.toString();
        } catch (Exception e) {
            log.warn("", e);
            return templateVal;
        } finally {
            try {
                configuration.removeTemplateFromCache(name);
            } catch (Exception e) {
                log.warn("", e);
            }
        }
    }

    private Map<String, Object> getRootUrlMap() {
        return new HashMap<String, Object>() {{
            put("rootUrl", ssoConfig.getSelfRootUrlByRequest());
        }};
    }
}
